#!/usr/bin/bash
set -euo pipefail

TARGET_CPU=riscv64
SYSROOT=/usr/lib/riscv64-linux-gnu/sys-root/

TARGET=$TARGET_CPU-linux-gnu
BUILDARCH=$(uname -p)

[ "$BUILDARCH" = "$TARGET_CPU" ] && TARGET_PREFIX="" || TARGET_PREFIX="${TARGET}-"

export CC=${TARGET_PREFIX}gcc
export CXX=${TARGET_PREFIX}g++
export AR=${TARGET_PREFIX}ar
export AS=${TARGET_PREFIX}as
export LD=${TARGET_PREFIX}ld
export NM=${TARGET_PREFIX}nm
export OBJCOPY=${TARGET_PREFIX}objcopy
export OBJDUMP=${TARGET_PREFIX}objdump
export RANLIB=${TARGET_PREFIX}ranlib
export READELF=${TARGET_PREFIX}readelf
export STRIP=${TARGET_PREFIX}strip

export QEMU_LD_PREFIX=$SYSROOT

rpmbuild --target $TARGET \
	 --define "_cross_compiler_prefix $TARGET-" \
	 --define "_cross_compiling 1" \
	 --define "_build_arch $BUILDARCH" \
	 --define "__cc $CC" \
	 --define "__cxx $CXX" \
	 --define "__ar $AR" \
	 --define "__as $AS" \
	 --define "__ld $LD" \
	 --define "__nm $NM" \
	 --define "__ranlib $RANLIB" \
	 --define "__readelf $READELF" \
	 --define "__objcopy $OBJCOPY" \
	 --define "__objdump $OBJDUMP" \
	 --define "__strip $STRIP" \
	 --define "__os_install_post %{nil}" \
	 --define "__arch_install_post %{nil}" \
	 --define "_target_cpu ${TARGET_CPU}" \
	 --define "_host ${TARGET}" \
	 --define "_build $BUILDARCH-OpenCloudOS-linux-gnu" \
	 --define "_target_cflags -O2" \
	 --define "_target_ldflags %{nil}" \
	 --define "_without_check 1" \
	 --define "_disable_werror 1" \
	 $@
